package com.pca.headline.filters;

import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;

@WebFilter("/*")
public class CrosFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        HttpServletRequest request =(HttpServletRequest) servletRequest;
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, HEAD");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "access-control-allow-origin, authority, content-type, version-info, X-Requested-With");
        // 非预检请求,放行即可,预检请求,则到此结束,不需要放行
        if(!request.getMethod().equalsIgnoreCase("OPTIONS")){
            filterChain.doFilter(servletRequest, servletResponse);
        }
//        HttpServletResponse httpResponse = (HttpServletResponse) servletResponse;
//        HttpServletRequest httpRequest = (HttpServletRequest) servletRequest;
//
//        // 允许的域名（* 表示允许所有域名）
//        httpResponse.setHeader("Access-Control-Allow-Origin", "*");
//
//        // 允许的 HTTP 方法
//        httpResponse.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT,OPTIONS, DELETE, HEAD");
//
//        // 允许的请求头
//        httpResponse.setHeader("Access-Control-Allow-Headers", "access-control-allow-origin, authority, content-type, version-info, X-Requested-With");
//
//        // 是否允许携带凭证（如 Cookie）
//        //httpResponse.setHeader("Access-Control-Allow-Credentials", "true");
//
//        // 预检请求（OPTIONS）缓存时间（单位：秒）
//        httpResponse.setHeader("Access-Control-Max-Age", "3600");
//
//        // 如果是预检请求（OPTIONS），直接返回成功
//        if ("OPTIONS".equalsIgnoreCase(httpRequest.getMethod())) {
//            httpResponse.setStatus(HttpServletResponse.SC_OK);
//            return;
//        }
//
//        // 继续执行后续过滤器或目标资源
//        filterChain.doFilter(servletRequest, servletResponse);

    }
}